package ru.ifmo.croak.impl.remoting.post.team2.server;

import ru.ifmo.croak.api.Message;
import ru.ifmo.croak.api.PostService;
import ru.ifmo.croak.util.CroakFactory;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * Created by Евгений
 * Date: 18.05.11
 * Time: 16:22
 */
public class PostListener implements Runnable {
    private final PostService provider;
    private final Socket socket;
    public PostListener(String providerName, Socket socket) {
        provider = CroakFactory.getInstance().getImplementation(PostService.class, providerName);
        this.socket = socket;
    }
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            while (true) {
                Message message = getMessage(inputStream);
                provider.postMessage(message);
                String line = message.getId().toString()+'$';
                outputStream.write(line.getBytes());
            }

        } catch (Exception e) {

        }
    }

    private Message getMessage (InputStream inputStream) throws IOException {
        Message message = new Message();
        int c;
        String size = "";
        while((c=inputStream.read()) != '$') {
            size += c;
        }
        int messageSize = Integer.parseInt(size);
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        line = reader.readLine();
        messageSize -= line.length();
        message.setId(UUID.fromString(line));
        line = reader.readLine();
        messageSize -= line.length();
        message.setTime(Long.parseLong(line));
        line = reader.readLine();
        messageSize -= line.length();
        message.setAuthor(line);
        messageSize -= 3;
        line = "";
        for(int i = 0; i < messageSize; i++) {
            line += inputStream.read();
        }
        message.setText(line);
        return message;
    }
}
